using System;
using System.Collections.Generic;
using Sedge.Core.App;

namespace Sedge.Core.Configuration
{
	public class FilesRegistry
	{
		private readonly Suite _suite;

		public delegate bool OneFileReportDelegate(string file);
		private readonly List<RegisteredFileInfo> _registeredFiles = new List<RegisteredFileInfo>();

		public int Count
		{
			get { return _registeredFiles.Count; }
		}

		public FilesRegistry(Suite suite)
		{
			_suite = suite;
		}

		public int Register(string path, FileType fileType)
		{
			RegisteredFileInfo registeredFileInfo = new RegisteredFileInfo(fileType, path);
			_registeredFiles.Add(registeredFileInfo);
			return _registeredFiles.Count - 1;
		}

		public RegisteredFileInfo GetFile(int pathID)
		{
			if (pathID < 0 || pathID >= _registeredFiles.Count)
				return null;

			return _registeredFiles[pathID];
		}

		public void CopyFiles(OneFileReportDelegate reportDelegate)
		{
			foreach (RegisteredFileInfo fileInfo in _registeredFiles)
			{
				if (!reportDelegate(fileInfo.OriginalPath))
					return;

				if (!Services.FileSystem.File.Exists(fileInfo.OriginalPath))
					continue;

				string relFolder;
				string destPath = GetDestPath(fileInfo.FileType, out relFolder);
				string fileName = Services.FileSystem.Path.GetFileNameWithoutExtension(fileInfo.OriginalPath);
				string fileExt = Services.FileSystem.Path.GetExtension(fileInfo.OriginalPath);

				int counter = 1;
				string fileNameExt = Services.FileSystem.Path.Combine(destPath,
														  Services.FileSystem.Path.GetFileName(fileInfo.OriginalPath));
				while (Services.FileSystem.File.Exists(fileNameExt))
				{
					fileNameExt = Services.FileSystem.Path.Combine(destPath,
							 String.Format("{0}{1:D3}.{2}", fileName, counter, fileExt));
					counter++;
				}

				Services.FileSystem.File.Copy(fileInfo.OriginalPath, fileNameExt);
				fileInfo.NewPath = String.Format("..\\{0}\\{1}", 
											relFolder, Services.FileSystem.Path.GetFileName(fileNameExt));
				fileInfo.Valid = true;
			}
		}

		private string GetDestPath(FileType fileType, out string relFolder)
		{
			string destPath;
			switch (fileType)
			{
				case FileType.File:
					destPath = _suite.FilesFolder;
					relFolder = Branding.ReportFiles;
					break;
				case FileType.UserFile:
					destPath = _suite.UserFilesFolder;
					relFolder = Branding.ReportUserFiles;
					break;
				case FileType.Image:
					destPath = _suite.ImagesFolder;
					relFolder = Branding.ReportImages;
					break;
				default:
					destPath = _suite.FilesFolder;
					relFolder = Branding.ReportFiles;
					break;
			}

			return destPath;
		}
	}
}